import React from 'react';

import { Dispatch, State } from './types';
import navigator from '../../../../util/navigator';
import { modalOpen } from '../../../../util/global';
import { UserApi } from '../../../../api';
import SendLogAlert, { sendFrontLog } from './components/SendLog';
import { systemUtil } from '../../../../util/native';
import { DEVICE_BRAND_VIVO } from '../../../../constant';

let dispatch: Dispatch;
let state: State;

export default (d: Dispatch, s: State): void => {
  dispatch = d;
  state = s;
};

export const fetchSuccess = (value: any): void => {
  dispatch({ type: 'FETCH_SUCCESS', value });
};

export const fetchFailed = (): void => {
  dispatch({ type: 'FETCH_FAILED' });
};

export const getSelfCenter = (): void => {
  UserApi.getSelfCenter()
    .then((res): void => {
      if (res.code === 0) {
        fetchSuccess(res.data);
      } else {
        fetchFailed();
      }
    })
    .catch((): void => {
      fetchFailed();
    });
};

export const onPressPersonalInfo = (): void => {
  const { data } = state;
  const { headPortraitURL, nickName, gender } = data;
  navigator.push('PersonalInfo', {
    headPortrait: headPortraitURL,
    nickName,
    gender
  });
};

export const onPressCharge = (): void => {
  navigator.push('Charge');
};

export const onPressContact = (): void => {
  navigator.push('Contact');
};

export const onPressSet = (): void => {
  navigator.push('Setting');
};

export const onPressOrderList = (): void => {
  navigator.push('OrderList');
};

export const onPressAddress = (): void => {
  navigator.push('ReceiveAddress');
};

export const onPressSendLog = (): void => {
  if (systemUtil.getDeviceProduct() === DEVICE_BRAND_VIVO) {
    sendFrontLog(false);
    navigator.push('FeedBack');
    return;
  }
  modalOpen({
    Type: (): React.ReactElement => <SendLogAlert />,
    needBack: true,
    needBlur: true
  });
};
